package net.valerijtimakov.homefinances.dao.storages.common.mysql.query_builders.condition;

import net.valerijtimakov.homefinances.domain.common.CheckedData;
import net.valerijtimakov.homefinances.exceptions.AppExceptionWrongState;
import net.valerijtimakov.homefinances.dao.storages.common.mysql.query_builders.MySqlUtils;

public class IntervalConditionBuilder<T> extends CheckedData {
	
	private String fieldName;
	private T fromValue;
	private T toValue;
	private boolean fromStrict;
	private boolean toStrict;
	
	public IntervalConditionBuilder() {
		super();
	}
	
	public IntervalConditionBuilder(String fieldName) {
		this();
		this.fieldName = fieldName;
	}

	public String getFieldName() {
		return fieldName;
	}

	public void setFieldName(String fieldName) {
		this.fieldName = checkNull(fieldName);
	}

	public T getFromValue() {
		return fromValue;
	}

	public void setFromValue(T fromValue) {
		this.fromValue = fromValue;
	}

	public T getToValue() {
		return toValue;
	}

	public void setToValue(T toValue) {
		this.toValue = toValue;
	}
	
	public boolean isFromStrict() {
		return fromStrict;
	}

	public void setFromStrict(boolean fromStrict) {
		this.fromStrict = fromStrict;
	}

	public boolean isToStrict() {
		return toStrict;
	}

	public void setToStrict(boolean toStrict) {
		this.toStrict = toStrict;
	}

	public void addCondition(StringBuilder condition) throws AppExceptionWrongState {
		if (fieldName.isEmpty() && (fromValue != null || toValue != null)) {
			throw new AppExceptionWrongState("Не задано имя поля!");
		}
		if (fromValue == null && toValue == null) {
			return;
		}
		if (condition.length() > 0) {
			condition.append(" AND ");
		}
		condition.append("`");
		condition.append(fieldName);
		if (fromValue != null) {
			condition.append("`>");
			if (!fromStrict) {
				condition.append("=");
			}
			condition.append(MySqlUtils.getValueLine(fromValue));
			if (toValue != null) {
				condition.append(" AND `");
				condition.append(fieldName);
				condition.append("`<");
				if (!toStrict) {
					condition.append("=");
				}
				condition.append(MySqlUtils.getValueLine(toValue));
			}
		} else {
			condition.append("`<");
			if (!toStrict) {
				condition.append("=");
			}
			condition.append(toValue);
		}
		condition.append(" ");
	}
	
}
